package org.ooda.distributedsys.loginmodule.controllers;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.ooda.distributedsys.loginmodule.common.ResponseHandler;
import org.ooda.distributedsys.loginmodule.entity.User;
import org.ooda.distributedsys.loginmodule.functions.ShaUtils;
import org.ooda.distributedsys.loginmodule.services.UserServiceImp;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;

/**
 * @program: distributedSys
 * @description: 用户登录接口
 * @author: Aprilies
 * @create: 2023-03-16 00:06
 **/

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImp userServiceImp;

    @PostMapping("login")
    public ResponseEntity<?> login(@RequestBody User user) throws NoSuchAlgorithmException {

        // verify whether the username and password is correct
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        Wrapper<User> eq = wrapper.eq("username", user.getUsername());
        User one = userServiceImp.getOne(eq);
        if(one == null){
            return ResponseHandler.generateResponse("username or password is wrong", HttpStatus.RESET_CONTENT, null);
        }
        if(!one.getPassword().equals(ShaUtils.sha(user.getPassword()))){
            return ResponseHandler.generateResponse("username or password is wrong", HttpStatus.RESET_CONTENT, null);
        }
        // get a cookie for this user
        String s = Jwts.builder().setSubject(user.getPassword())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 有效期1小时
                .signWith(SignatureAlgorithm.HS256, "mysecretkey")
                .compact();
        HashMap<String, String> wrapperMap = new HashMap<>();
        wrapperMap.put("Authorization", s);
        return ResponseHandler.generateResponse("login success", HttpStatus.OK, wrapperMap);
    }

    @PostMapping("logout")
    public ResponseEntity<?> logout(){
        return ResponseEntity.ok("退出成功");
    }

    public ResponseEntity<?> register(@RequestParam("username") String username,
                                       @RequestParam("password") String password) throws NoSuchAlgorithmException {
        // check is username already exists
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        Wrapper<User> eq = wrapper.eq("username", username);
        User one = userServiceImp.getOne(eq);
        if(one!= null){
            return ResponseHandler.generateResponse("username already exists", HttpStatus.RESET_CONTENT, null);
        }
        User user = new User();
        user.setId(null);
        user.setUsername(username);
        String passwordSha = ShaUtils.sha(password);
        user.setPassword(passwordSha);
        user.setCreate_at(new Date());
        userServiceImp.save(user);
        return ResponseHandler.generateResponse("register success", HttpStatus.OK, null);
//                ResponseEntity.ok("注册成功");
    }

    @PostMapping("register")
    public ResponseEntity<?> register(@RequestParam("newUserName") String newUserName,
                                      @RequestParam("newPassword") String newPassword,
                                      @RequestBody User user) throws NoSuchAlgorithmException {
        if(newUserName.equals(user.getUsername())) {
            return ResponseHandler.generateResponse("username already exists", HttpStatus.RESET_CONTENT, null);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        Wrapper<User> eq = wrapper.eq("username", user.getUsername());
        User one = userServiceImp.getOne(eq);
        if(one == null){
            return ResponseHandler.generateResponse("username or password is wrong", HttpStatus.RESET_CONTENT, null);
        }
        if(!one.getPassword().equals(ShaUtils.sha(user.getPassword()))){
            return ResponseHandler.generateResponse("username or password is wrong", HttpStatus.RESET_CONTENT, null);
        }
        User newUser = new User();
        newUser.setId(null);
        newUser.setUsername(newUserName);
        String passwordSha = ShaUtils.sha(newPassword);
        newUser.setPassword(passwordSha);
        newUser.setCreate_at(new Date());
        userServiceImp.save(newUser);
        return ResponseHandler.generateResponse("register success", HttpStatus.OK, null);
    }

    @GetMapping("isLogin")
    public ResponseEntity<?> isLogin(@RequestHeader(value = "Authorization",required = false) String token){
        return ResponseHandler.generateResponse("login success", HttpStatus.OK, null);
    }
}
